package com.leetcode.p100;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;

public class Test127 {

    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> wordSet = new HashSet<>(wordList);
        if (wordSet.size() == 0 || !wordSet.contains(endWord)) {
            return 0;
        }

        wordSet.remove(beginWord);

        Set<String> visited = new HashSet<>();
        visited.add(beginWord);

        Queue<String> queue = new LinkedList<>();
        queue.add(beginWord);

        int step = 1;

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                String currentWord = queue.poll();
                if (changeWordEveryOneLetter(currentWord, endWord, wordSet, visited, queue)) {
                    return step + 1;
                }
            }
            step++;
        }

        return 0;
    }

    private boolean changeWordEveryOneLetter(String currentWord, String endWord, Set<String> wordSet, Set<String> visited, Queue<String> queue) {
        char[] charArray = currentWord.toCharArray();

        for (int i = 0; i < charArray.length; i++) {
            char currentChar = charArray[i];
            for (char k = 'a'; k <= 'z'; k++) {
                if (k == currentChar) {
                    continue;
                }

                charArray[i] = k;
                String nextWord = String.valueOf(charArray);

                if (wordSet.contains(nextWord)) {
                    if (nextWord.equals(endWord)) {
                        return true;
                    }

                    if (!visited.contains(nextWord)) {
                        visited.add(nextWord);
                        queue.add(nextWord);
                    }
                }
            }
            charArray[i] = currentChar;
        }
        return false;
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("hot");
        list.add("dot");
        list.add("dog");
        list.add("lot");
        list.add("log");
        list.add("cog");

        Test127 test = new Test127();
        int a = test.ladderLength("hit", "cog", list);
        System.out.println(a);
    }

}
